package Z11_4_synchronizedControl;

/**
 * @author： pang-yun
 * @date： 2021-11-04 15:13
 * 功能目的 ：用于  thread 交替输出
 *                  使用 wait  notify  的方式
 */

public class Alternate {

    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify();
        new Thread(()->{
            waitNotify.print("a",1,2);
        }).start();

        new Thread(()->{
            waitNotify.print("b",2,3);
        }).start();


        new Thread(()->{
            waitNotify.print("c",3,1);
        }).start();
    }
    }


class WaitNotify {
    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this) {
                while (flag != waitFlag) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }

    private int loopNumber = 5;
    private int flag = 1;
}